<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\BaseController as AppBaseController;
use app\model\Model;
use think\facade\Request;

class BaseController extends AppBaseController
{
    public $admin;
    public $lang;
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        'login',
        'auth',
    ];

    public function initialize()
    {
        parent::initialize();
        self::createInstallFile();
        $this->admin = $this->request->admin;
        $this->lang = config('lang.allow_lang_list');
    }

    public function setLimit(): int
    {
        $limit = 10;
        $limitPage = (int)input('param.limit');
        if($limitPage){
            $limit = $limitPage;
        }
        return $limit;
    }

    private static function createInstallFile()
    {
        $installFile = app()->getRootPath().'data/install.lock';
        if(!file_exists($installFile) && file_exists(app()->getRootPath().'data/install/')){
            $url = env('app_host') . '/install';
            redirect($url);
        }else{
            touch($installFile);
        }
    }

    public function customDelete($opt,$title='批量删除'): \think\response\Json
    {
        $ids = $this->request->param('id');
        if(is_string($ids)){
            $ids = explode(',',$ids);
        }
        $className = str_replace('backend.','',Request::controller());
        $modelName =  '\\app\\model\\' . $className;
        $model = new $modelName();
        try{
            $model->whereIn('id',$ids)->delete();
            optEventLog(json_encode($ids),$title,$opt);
        }catch (\Exception $e){
            return jsonReturn(-1,'删除失败');
        }
        return jsonReturn(0,'删除成功');
    }

    public function customSoftDelete($opt,$title='批量删除'): \think\response\Json
    {
        $ids = $this->request->param('id');
        if(is_string($ids)){
            $ids = explode(',',$ids);
        }
        $className = str_replace('backend.','',Request::controller());
        $modelName =  '\\app\\model\\' . $className;
        $model = new $modelName();
        try{
            $model->whereIn('id',$ids)->update(['is_del'=>2,'delete_time'=>time()]);
            optEventLog(json_encode($ids),$title,$opt);
        }catch (\Exception $e){
            return jsonReturn(-1,'删除失败');
        }
        return jsonReturn(0,'删除成功');
    }
}
